//
//  YZAutoTVCell.m
//  VET
//
//  Created by Lam BG on 2018/7/12.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZAutoTVCell.h"

#import "YZAutoRowModel.h"

@interface YZAutoTVCell ()

@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (weak, nonatomic) IBOutlet UILabel *numLabel;

@end



@implementation YZAutoTVCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    [self setupTextView];
    
    @weakify(self);
    [self.textView.rac_textSignal subscribeNext:^(NSString *content) {
        
        @strongify(self);
        // 输入限制
        NSInteger kMaxLength = self.textSize;
        NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;
        if ([lang isEqualToString:@"zh-Hans"]) {
            
            // 中文输入
            UITextRange *selectedRange = [self.textView markedTextRange];
            // 获取高亮部分
            UITextPosition *position = [self.textView positionFromPosition:selectedRange.start offset:0];
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                if (content.length > kMaxLength) {
                    
                    content = [content substringToIndex:kMaxLength];
                    self.textView.text = content;
                }
                
                self.rowModel.displayValue = self.rowModel.paramValue = content;
                self.numLabel.text = [NSString stringWithFormat:@"%ld/%ld", content.length, self.textSize];
            } else {
                // 有高亮选择的字符串，则暂不对文字进行统计和限制
            }
        } else {
            
            // 不考虑限制
            if (content.length > kMaxLength) {
                
                content = [content substringToIndex:kMaxLength];
                self.textView.text = content;
            }
            
            self.rowModel.displayValue = self.rowModel.paramValue = content;
            self.numLabel.text = [NSString stringWithFormat:@"%ld/%ld", content.length, self.textSize];
        }
    }];
}

- (void)setupTextView {
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"点击输入任务内容...";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [self.textView addSubview:placeHolderLabel];
    
    // same font
    self.textView.font = [UIFont systemFontOfSize:14.f];
    placeHolderLabel.font = [UIFont systemFontOfSize:14.f];
    
    [self.textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}

#pragma mark - 子类实现
- (void)setupCellView {
    [super setupCellView];
    
    self.textView.text = self.rowModel.displayValue;
    self.numLabel.text = [NSString stringWithFormat:@"%ld/%ld", self.textView.text.length, self.textSize];
}


@end



